package persistence

import (
	"context"
	"zxstudy.com/domain/entity"
	"zxstudy.com/infrastructure/ent"
	"zxstudy.com/infrastructure/ent/group"
)

type Groups struct {
	client *ent.Client
}

func NewGroupRepository(client *ent.Client) *Groups {
	return &Groups{
		client: client,
	}
}

func (g *Groups) Create(ctx context.Context, group *entity.Group) (*entity.Group, error) {
	gc := g.client.Group.
		Create().
		SetName(group.Name)
	if len(group.Users) > 0 {
		ids := make([]int, 0, len(group.Users))
		for _, user := range group.Users {
			ids = append(ids, user.ID)
		}
		gc.AddUserIDs(ids...)
	}
	gr, err := gc.Save(ctx)
	if err != nil {
		return nil, err
	}

	return gr.ToDomain(), nil
}

func (g *Groups) Get(ctx context.Context, id int) (*entity.Group, error) {
	gr, err := g.client.Group.
		Query().
		Where(group.ID(id)).
		Only(ctx)
	if err != nil {
		return nil, err
	}
	
	return gr.ToDomain(), nil
}

func (g *Groups) Groups(ctx context.Context) ([]*entity.Group, error) {
	groups, err := g.client.Group.
		Query().
		All(ctx)
	if err != nil {
		return nil, err
	}

	newGrs := make([]*entity.Group, 0, len(groups))
	for _, gr := range groups {
		newGrs = append(newGrs, gr.ToDomain())
	}
	
	return newGrs, nil
}